/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed analysisPptPath in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.biglead.demo.job.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.biglead.demo.job.utils.CronUtils;
import com.biglead.demo.mapper.ScheduleJobDao;
import com.biglead.demo.pojo.ScheduleJobEntity;
import com.biglead.demo.job.service.ScheduleJobService;
import com.biglead.demo.job.utils.Constant;
import com.biglead.demo.job.utils.ScheduleUtils;
import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;

@Service("scheduleJobService")
public class ScheduleJobServiceImpl extends ServiceImpl<ScheduleJobDao, ScheduleJobEntity> implements ScheduleJobService {
    @Resource
    private Scheduler scheduler;

    /**
     * 项目启动时，初始化定时器
     */
    @PostConstruct
    public void init() {
        //查询当前所有的定时任务
        List<ScheduleJobEntity> scheduleJobList = this.list(new QueryWrapper<>());
        try {
            scheduler.clear();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        for (ScheduleJobEntity scheduleJob : scheduleJobList) {
            //获取任务的表达式触发器
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
            //如果不存在，则创建
            if (cronTrigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
            } else {
                ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
            }
        }
    }

    @Override
    public Page<ScheduleJobEntity> queryPage(Map<String, Object> params) {
        String beanName = (String) params.get("bea nName");
        //分页查询数据
        Page<ScheduleJobEntity> userPage = new Page<>(1,2);

        //分页查询的结果
        Page<ScheduleJobEntity> page = this.page(userPage, new QueryWrapper<ScheduleJobEntity>());


        return page;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean newObj(ScheduleJobEntity scheduleJob) {
        scheduleJob.setCreateTime(new Date());
        //设置状态 默认是启动
        scheduleJob.setStatus(Constant.ScheduleStatus.NORMAL.getValue());
        //cron表达式
        String cronExpression = scheduleJob.getCronExpression();
        //验证
        boolean valid =  CronExpression.isValidExpression(cronExpression);
        if(!valid){
            throw new RuntimeException("cron 表达式不正确");
        }
        //保存任务
        this.save(scheduleJob);
        //构建job信息
        ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ScheduleJobEntity scheduleJob) {
        ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
        //更新数据库
        this.updateById(scheduleJob);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] jobIds) {
        for (Long jobId : jobIds) {
            ScheduleUtils.deleteScheduleJob(scheduler, jobId);
        }
        //删除数据
        this.deleteBatch(jobIds);
    }

    @Override
    public int updateBatch(Long[] jobIds, int status) {
        Map<String, Object> map = new HashMap<>();
        map.put("list", jobIds);
        map.put("status", status);
        return baseMapper.updateBatch(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void run(Long[] jobIds) {
        for (Long jobId : jobIds) {
            ScheduleUtils.run(scheduler, this.getById(jobId));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pause(Long[] jobIds) {
        for (Long jobId : jobIds) {
            ScheduleUtils.pauseJob(scheduler, jobId);
        }

        updateBatch(jobIds, Constant.ScheduleStatus.PAUSE.getValue());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resume(Long[] jobIds) {
        for (Long jobId : jobIds) {
            ScheduleUtils.resumeJob(scheduler, jobId);
        }

        updateBatch(jobIds, Constant.ScheduleStatus.NORMAL.getValue());
    }

}
